package com.renwei.yunlong.activity.contacts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.CommonSearchActivity;
import com.renwei.yunlong.activity.news.TranspaintActivity;
import com.renwei.yunlong.adapter.SortContactAdapter;
import com.renwei.yunlong.adapter.StartChatListAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.bean.contacts.DepartmentContactBean;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.event.ContactCheckEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.ContactPingyinComparator;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PinyinUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.SearchImage;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


/**
 * Project :  yunaandroid.
 * Package name: com.renwei.yunlong.activity.contacts
 * Created by :  Benjamin.
 * Created time: 2017/11/28 17:21
 * Changed by :  Benjamin.
 * Changed time: 2017/11/28 17:21
 * Class description:
 */
public class SeeContactsByDepartmentActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, SwipeRefreshLayout.OnRefreshListener {


    private static int from_type = 0;
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.lv_function_list)
    ListView lvFunctionList;
    @Bind(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    List<Contact> contactList;
    @Bind(R.id.search_image)
    SearchImage searchImage;
    View headerView;
    LinearLayout headerContain;
    @Bind(R.id.btn_commit)
    Button btnCommit;
    @Bind(R.id.rlv_bottom_contact)
    RecyclerView rlvBottomContact;
    @Bind(R.id.pannel_bottom)
    RelativeLayout pannelBottom;
    private StartChatListAdapter bottomListAdapter;
    //根据拼音来排列ListView里面的数据类
    private ContactPingyinComparator contactPingyinComparator;
    private SortContactAdapter sortContactAdapter;

    //添加联系人页面跳转过来
    public static void openactivity(Context context, int from_type) {
        Intent intent = new Intent(context, SeeContactsByDepartmentActivity.class);
        intent.putExtra("from_type", from_type);
        context.startActivity(intent);
    }

    //添加联系人页面跳转过来
    public static void openactivity(Context context, int from_type, String departmentId) {
        Intent intent = new Intent(context, SeeContactsByDepartmentActivity.class);
        intent.putExtra("from_type", from_type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_see_contacts_by_department);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        swipeRefresh.setOnRefreshListener(this);
        searchImage.setOnClickListener(this);
        rlvBottomContact.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        bottomListAdapter = new StartChatListAdapter(this, companyType);
        rlvBottomContact.setAdapter(bottomListAdapter);
        from_type = getIntent().getIntExtra("from_type", 0);
        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TranspaintActivity.openActivity(SeeContactsByDepartmentActivity.this);
                //EventBus.getDefault().post(new CommitMemberEvent(CommitMemberEvent.COMMIT_MEMBER_EVENT));
            }
        });
        if (from_type == 0) {
            pannelBottom.setVisibility(View.GONE);
        } else {
            pannelBottom.setVisibility(View.VISIBLE);
        }
        onRefresh();
    }

    private void initData() {
        simpleTileView.setTitle("按部门查看");
        headerView = LayoutInflater.from(this).inflate(R.layout.item_function_header, null, false);
        headerContain = headerView.findViewById(R.id.container);
        sortContactAdapter = new SortContactAdapter(this, from_type, companyType, contactList);
        if (lvFunctionList.getHeaderViewsCount() == 0) {
            lvFunctionList.addHeaderView(headerView);
        }
        lvFunctionList.setAdapter(sortContactAdapter);
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        String userId = "0";
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            userId = ownerBean.getRows().getEmployeeId();
        } else if ("2".equals(companyType)) {
            userId = serviceLoginBean.getRows().getEmployeeId();
        }
        map.put("currentUserId", userId);
        swipeRefresh.setRefreshing(true);
        manager.queryContactByDepartmentOne(this, JsonMapUtil.mapToJson(map), this);
        // 实例化汉字转拼音类
        contactPingyinComparator = new ContactPingyinComparator();
        initBottomContactList();
    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("按部门查看 " + result);
        switch (requestId) {
            case 1:
                DepartmentContactBean bean = new Gson().fromJson(result, DepartmentContactBean.class);
                initListData(bean);
                break;
            default:
                break;
        }
    }

    private void initListData(DepartmentContactBean bean) {
        contactList = new ArrayList<>();
        if (bean != null && bean.getRows() != null && UtilList.getCount(bean.getRows()) > 0) {
            for (Contact item : bean.getRows()) {
                if ("0".equals(item.getDepartmentId())) {
                    contactList.add(item);
                } else {
                    headerContain.addView(getView(item));
                }
            }
            contactList = filledPingYing(contactList);
            Collections.sort(contactList, contactPingyinComparator);
            sortContactAdapter.refresh(contactList);
        } else {
            //失败弹窗
        }
        swipeRefresh.setRefreshing(false);
    }

    //转拼音
    private List<Contact> filledPingYing(List<Contact> contactList) {
        for (int i = 0; i < contactList.size(); i++) {
            Contact appEmployee = contactList.get(i);
            if (appEmployee != null) {
                String name = appEmployee.getName();
                //汉字转换成拼音
                String pinyin = PinyinUtils.getPingYin(name);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    appEmployee.setLetter(sortString.toUpperCase());
                } else {
                    appEmployee.setLetter("#");
                }
            }

        }
        return contactList;
    }

    private View getView(final Contact item) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_function_group, null, false);
        TextView groupName = view.findViewById(R.id.tv_function_name);
        TextView gropCount = view.findViewById(R.id.tv_function_fount);
        LinearLayout itemFunction = view.findViewById(R.id.item_function);
        groupName.setText(StringUtils.value(item.getDepartmentName()));
        gropCount.setText(Integer.valueOf(item.getConuntEmployee())+" 人");
        itemFunction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (item.getConuntEmployee() > 0) {
                    ContactListActivity.openActivity(SeeContactsByDepartmentActivity.this, "2", null,
                            item.getDepartmentId(), StringUtils.value(item.getDepartmentName()), from_type);
                } else {
                    showCenterInfoMsg("该部门没有人员");
                }
            }
        });
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefreshName(ContactCheckEvent event) {
        initBottomContactList();
        if (sortContactAdapter != null) {
            sortContactAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onClosePage(ChatListCloseEvent event) {
        finish();
    }


    public void initBottomContactList() {
        bottomListAdapter.setData(AppHelper.getCheckContactList());
        String commitText = "";
        if (UtilList.getCount(AppHelper.getCheckContactList()) == 0) {
            commitText = "确定";
        } else {
            commitText = "确定(" + UtilList.getCount(AppHelper.getCheckContactList()) + ")";
        }
        btnCommit.setText(commitText);
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }


    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.search_image:
                CommonSearchActivity.OpenActivityFromContact(this, v, SeeContactsByDepartmentActivity.class, 999, from_type, companyType);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }


}
